(function(avalon, $, Api) {
	var dkLink = 'http://daka.sudiyi.cn/api/record';
	var UserInfo = JSON.parse(localStorage.getItem('UserInfo')) || {
		appid: 'A6902492686066',
		appkey: '94464404-A974-827B-A63B-5C526783CC9E'
	};
	avalon.effect('menuShowHide', {
		enterClass: 'menuShow',
		leaveClass: 'menuHide'
	});
	var dateVm;
	var vm = avalon.define({
		$id: 'main',
		menuShowMark: false,
		passportShow: typeof UserInfo.user === 'undefined',
		passpordpage: 'login',
		loginModel: {
			username: '',
			password: '',
			submit: function(e){
				e.preventDefault();
				ajaxBind({
					url: '/mcm/api/user/login',
					method: 'post',
					data: {
						username: vm.loginModel.username,
						password: vm.loginModel.password
					},
					type: 'post',
					success: function(data){
						console.log(data);
						UserInfo.user = {
							userId: data.userId,
							token: data.id,
							username: vm.loginModel.username
						};
						localStorage.setItem('UserInfo', JSON.stringify(UserInfo));
						vm.passportShow = false;
					},
					error: function(err){
						vm.pMessage = '登录失败，请确认帐号密码重试！';
						vm.pMessageShow = true;
						setTimeout(function(){
							vm.pMessageShow = false;
						}, 3000);
					}
				});
			}
		},
		registModel: {
			username: '',
			password: '',
			repassword: '',
			uudi: '',
			submit: function(e){
				e.preventDefault();
				ajaxBind({
					url: '/mcm/api/user',
					method: 'post',
					data: {
						username: vm.registModel.username,
						password: vm.registModel.password,
						uuid: vm.registModel.uuid
					},
					type: 'post',
					success: function(data){
						console.log(data);
						if(!data.error){
							//success
							vm.pMessage = '注册成功，跳转去登录！';
							vm.pMessageShow = true;
							setTimeout(function(){
								vm.passpordpage = 'login';
								vm.pMessageShow = false;
							}, 3000);
						}
					},
					error: function(err){
						vm.pMessage = '注册失败，请确认帐号密码重试！';
						vm.pMessageShow = true;
						setTimeout(function(){
							vm.pMessageShow = false;
						}, 3000);
					}
				});
			}
		},
		pMessageShow:false,
		pMessage: '',
		changeLoginPage: function(page){
			vm.passpordpage = page;
		},
		btnText: (function() {
			var d = new Date().getHours();
			if (d > 8 && d < 12) return '上班';
			if (d > 15 && d < 21) return '下班';
			return '测试';
		})(),
		dateConfig: {
			$ready: function(vm) {
				dateVm = vm;
			},
			onRefreshRendArr: function(dateArr, m) {
				ajaxBind({
					url: '/mcm/api/dakaRecord',
					data: {
						'filter': '{"where":{"month": "'+ m +'"}}'
					},
					success: function(data) {
						mixDateInfo(dateArr, data);
					}
				});
			}
		},
		showMenu: function() {
			vm.menuShowMark = true;
		},
		hideMenu: function() {
			vm.menuShowMark = false;
		},
		gotoToday: function() {
			dateVm.changeMonth(dateVm.thisDate.year, dateVm.thisDate.month);
		},
		gotodk: function(){
			if(UserInfo.user.uuid) return startDaka(UserInfo.user.uuid);
			ajaxBind({
				url: '/mcm/api/user/' + UserInfo.user.userId,
				method: 'GET',
				success: function(data){
					UserInfo.user.uuid = data.uuid;
					localStorage.setItem('UserInfo', JSON.stringify(UserInfo));
					startDaka(data.uuid);
				}
			});
		}
	});

	function startDaka(uuid){
		pushDaka();
		// Api.ajax({
		// 	url: dkLink,
		// 	data: {
		// 		uuid: uuid
		// 	},
		// 	headers: {
		// 		referer: 'http://daka.sudiyi.cn'
		// 	},
		// 	success: function(data){
		// 		alert(JSON.stringify(data));
		// 		pushDaka();
		// 	}
		// });
	}

	function pushDaka(){
		var lastDkObj = JSON.parse(localStorage.getItem('dk'));
		var now = new Date().getTime();
		var dktype = (function(){
			var h = new Date().getHours();
			if(h >= 8 && h <= 10) return 'start';
			if(h >= 18 && h <= 20) return 'end';
			return 'other'; 
		})();
		if($.isEmptyObject(lastDkObj)) lastDkObj = {
			type: null,
			time: 0
		};

		if(dktype === 'other'){
			//其他时段
			if(confirm('正在其他时间段，的确要去签到？')){
				var type = lastDkObj.type === 'start' ? 'end' : 'start';
				ajaxDaka(type);
			}
		} else {
			if(dktype === 'end'){
				if(( now - lastDkObj.time ) < 9 * 60 * 60 * 1000) {
					//时间没到
					if(confirm('时间没到，确实签到？')){
						ajaxDaka(dktype);
					}
				}
			} else {
				ajaxDaka(dktype);
			}
			
		}
	}

	function ajaxDaka(type){
		var date = new Date();
		if(type === 'start'){
			ajaxBind({
				url: '/mcm/api/dakaRecord',
				type: 'post',
				data: {
					month: date.getFullYear() + '-' + (date.getMonth() + 1), 
					date: date.getDate(), 
					dkstart: true,
					user_id: UserInfo.user.userId
				},
				success: function(data){
					localStorage.setItem('dk', JSON.stringify({
						type: type,
						time: new Date().getTime(),
						id: data.id
					}));
				}
			});
		} else {
			if(!lastDkObj.id){
				ajaxBind({
					url: '/mcm/api/dakaRecord',
					type: 'post',
					data: {
						month: date.getFullYear() + '-' + (date.getMonth() + 1), 
						date: date.getDate(), 
						dkend: true,
						user_id: UserInfo.user.userId
					},
					success: function(data){
						localStorage.setItem('dk', JSON.stringify({
							type: type,
							time: new Date().getTime()
						}));
					}
				});
			} else {
				ajaxBind({
					url: '/mcm/api/dakaRecord/' + lastDkObj.id,
					type: 'put',
					data: {
						dkend: true
					},
					success: function(data){
						localStorage.setItem('dk', JSON.stringify({
							type: type,
							time: new Date().getTime()
						}));
					}
				});
			}
		}
	}


	function ajaxBind(options) {
		var date = new Date().getTime();
		options.url = 'https://d.apicloud.com' + options.url;
		options = $.extend(options, {
			cache: false,
			headers: {
				'X-APICloud-AppId': UserInfo.appid,
				'X-APICloud-AppKey': sha1(UserInfo.appid + 'UZ' + UserInfo.appkey + 'UZ' + date) + '.' + date
			}
		});
		$.ajax(options);
	}

	function mixDateInfo(dates, ajaxDates){
		for(var i = 0; i < ajaxDates.length; i ++){
			for(var j = 0; j < dates.length; j ++){
				if(ajaxDates[i].date === dates[j].day){
					
					dates[j][ajaxDates[i].dktype] = true;
				}
			}
		}
		return dates;
	}

})(avalon, Zepto, window.api || Zepto);